import { listMyChartVoByPageUsingPost } from '@/services/luckbi/chartController';
import { useModel } from '@umijs/max';
import { Avatar, Card, List, message, Result } from 'antd';
import Search from 'antd/es/input/Search';
import ReactECharts from 'echarts-for-react';
import React, { useEffect, useState } from 'react';

/**
 * 添加图表ai请求
 * @constructor
 */
const MyChartPage: React.FC = () => {
  // 初始数据
  const initSearchParams = {
    current: 1,
    pageSize: 6,
    // sortField: 'createTime',
    // sortOrder: 'descend',
  };

  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({ ...initSearchParams });
  const [chartList, setChartList] = useState<API.Chart[]>();
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);

  // 获取当前用户的信息
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};

  // 加载数据方法
  const loadData = async () => {
    setLoading(true);
    try {
      const res = await listMyChartVoByPageUsingPost(searchParams);
      if (res.data) {
        setChartList(res.data?.records ?? []);
        setTotal(res.data.total ?? 0);
      }
    } catch (e: any) {
      message.error('获取历史失败：' + e.message);
    }
    setLoading(false);
  };

  // 页面首次加载的时候，触发
  useEffect(() => {
    loadData();
  }, [searchParams]);

  return (
    <div className="my-chart-page">
      <Search
        placeholder="请输入图表名称"
        loading={loading}
        enterButton
        onSearch={(value) => {
          // 改变搜索条件
          setSearchParams({
            ...initSearchParams,
            name: value,
          });
        }}
      />
      <div className="margin-16" />

      <List
        // itemLayout="vertical"
        // size="large"
        loading={loading}
        grid={{
          gutter: 16,
          xs: 1,
          sm: 1,
          md: 1,
          lg: 1,
          xl: 2,
          xxl: 2,
        }}
        pagination={{
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              current: page,
              pageSize: pageSize,
            });
            console.log(page);
          },
          current: searchParams.current,
          pageSize: searchParams.pageSize,
          total: total,
        }}
        dataSource={chartList}
        footer={
          <div>
            <b>Luck 智能数据分析</b> for you
          </div>
        }
        renderItem={(item) => (
          <List.Item key={item.id}>
            <Card>
              <List.Item.Meta
                avatar={<Avatar src={currentUser?.userAvatar} />}
                title={item.name}
                description={item.chartType ? '图表类型：' + item.chartType : ''}
              />
              <br />
              <>
                {item.status === 'wait' && (
                  <>
                    <Result
                      status="warning"
                      title="图表等待生成中"
                      subTitle={item.execMessage ?? '当前系统过于火热，请稍加等待...'}
                    />
                  </>
                )}
                {item.status === 'running' && (
                  <>
                    <Result
                      status="info"
                      title="图表正在生成中..."
                      subTitle={item.execMessage ?? '图表正在生成中...'}
                    />
                  </>
                )}
                {item.status === 'succeed' && (
                  <>
                    <p>
                      <strong>{'分析目标：' + item.goal}</strong>
                    </p>
                    <div style={{ marginBottom: 16 }}></div>
                    <Card>
                      <ReactECharts option={JSON.parse(item.genChart ?? '')} />
                    </Card>
                  </>
                )}
                {item.status === 'failed' && (
                  <>
                    <Result
                      status="error"
                      title="图表生成失败"
                      subTitle={item.execMessage ?? '图表生成失败，请稍后重试...'}
                    />
                  </>
                )}
              </>
              <div>
                {item?.createTime && '分析时间：' + new Date(item?.createTime).toLocaleString()}
              </div>
            </Card>
          </List.Item>
        )}
      />
    </div>
  );
};
export default MyChartPage;
